package com.imxinxin.common.tools.base64;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.FileSystems;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

public class Base64Tool {
    public static void main(String[] args) throws IOException {
        String in = "/Users/xieyuxin/Desktop/code-build/origin-build/build-base64/src/main/java/com/imxinxin/tool/b.txt";
        String out = "/Users/xieyuxin/Desktop/code-build/origin-build/build-base64/src/main/java/com/imxinxin/tool/Base64.txt";
        fileToBase64(in, out);
    }


    public static void fileToBase64(String inPath, String outPath) throws IOException {
        FileChannel in = null;
        FileChannel out;
        try {
            in = FileChannel.open(FileSystems.getDefault().getPath(inPath));
            out = FileChannel.open(FileSystems.getDefault().getPath(outPath), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        } catch (Exception e) {
            if (in != null) {
                in.close();
            }
            throw e;
        }
        fileToBase64(in, out);
    }

    public static void fileToBase64(FileChannel in, FileChannel out) throws IOException {
        try {
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(3 * 1024);
            ByteBuffer base64;
            while ((in.read(byteBuffer)) > 0) {
                byteBuffer.flip();
                base64 = Base64.getEncoder().encode(byteBuffer);
                byteBuffer.clear();
                out.write(base64);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (in != null && in.isOpen()) {
                in.close();
            }
            if (out != null && out.isOpen()) {
                out.close();
            }
        }
    }


}
